//
//  DTagsViewController.swift
//  Drop
//
//  Created by hushaohua on 2017/11/16.
//  Copyright © 2017年 init. All rights reserved.
//

import UIKit
import CoreData

class DTagsViewController: UITableViewController, NSFetchedResultsControllerDelegate {

    override init(style: UITableViewStyle) {
        super.init(style: .plain);
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.configNavigationItem();
        self.view.backgroundColor = UIColor.white;
        self.configTableView();
        
        self.requestNewest();
        self.tagsController.delegate = self;
    }
    
    func configTableView() -> Void{
        self.tableView.tableFooterView = UIView();
        self.tableView.rowHeight = 44;
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell");
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        self.tagsController.delegate = nil;
    }
    
    //MARK:-
    func requestNewest() -> Void{
        do{
            try self.tagsController.performFetch()
        }catch{
            let nserror = error as NSError
            fatalError("tags controller fetch error \(nserror), \(nserror.userInfo)")
        }
    }
    
    //MARK:- NSFetchedResultsController
    lazy var tagsController:NSFetchedResultsController<Tag> = {
        let request:NSFetchRequest = Tag.defaultFetchRequest();
        let sortDes:NSSortDescriptor = Tag.defaultSort();
        request.sortDescriptors = [sortDes];
        var controller:NSFetchedResultsController<Tag> = NSFetchedResultsController(fetchRequest: request, managedObjectContext: HStoreManager.defaultManger().context, sectionNameKeyPath: nil, cacheName: nil);
        return controller;
    }();
    
    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        print("will,count:\(self.tagsController.fetchedObjects!.count)")
        self.tableView.beginUpdates();
    }
    
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        print("did,count:\(self.tagsController.fetchedObjects!.count)")
        self.tableView.endUpdates();
    }
    
    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        print("change-count:\(self.tagsController.fetchedObjects!.count)")
        switch type {
        case .insert:
            self.tableView.insertRows(at: [newIndexPath!], with: .automatic);
        case .update:
            if (self.actionFinishHandler != nil){
                self.actionFinishHandler!(true);
                self.actionFinishHandler = nil;
            }
            self.tableView.reloadRows(at: [indexPath!], with: .automatic);
        case .delete:
            
            if (self.actionFinishHandler != nil){
                self.actionFinishHandler!(true);
                self.actionFinishHandler = nil;
            }
            self.tableView.deleteRows(at: [indexPath!], with: .automatic);
        default:
            break;
        }
    }
    
    //MARK:-
    func configNavigationItem() -> Void {
        let right:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(rightNavigationAction));
        self.navigationItem.rightBarButtonItem = right;
    }
    
    lazy var tagNewView:DNewTagActionView = {
        var view:DNewTagActionView = DNewTagActionView(frame: CGRect(x:0,y:0,width:self.view.bounds.size.width,height:self.view.bounds.size.height / 2));
        view.backgroundColor = UIColor(white:1,alpha:0.5);
        return view;
    }();
    
    @objc func rightNavigationAction() -> Void {
        self.tagNewView.showWithMask();
        self.tagNewView.textField.text = "";
    }
    
    //MARK:- tableView
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (self.tagsController.fetchedObjects != nil){
            return self.tagsController.fetchedObjects!.count;
        }
        return 0;
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath);
        let tag:Tag = self.tagsController.object(at: indexPath) as Tag;
        cell.textLabel?.text = tag.name;
        if (tag.histories != nil && tag.histories!.count > 0){
            cell.accessoryType = .disclosureIndicator;
        }else{
            cell.accessoryType = .none;
        }
        return cell;
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true);
        let tag:Tag = self.tagsController.object(at: indexPath) as Tag;
        if (tag.histories != nil && tag.histories!.count > 0){
            let controller:DTagHistoriesViewController = DTagHistoriesViewController(style: .plain);
            controller.tag = tag;
            self.navigationController?.pushViewController(controller, animated: true);
        }
    }
    
    //MARK: - editing
    var editingTag:Tag?;
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true;
    }
    lazy var cellEditActions:[UITableViewRowAction] = {
        let deleteAction:UITableViewRowAction = UITableViewRowAction(style: .default, title: "删除", handler: { (rowAction, indexPath) in
            self.editingTag = self.tagsController.object(at: indexPath) as Tag;
            self.showDeleteConfirmAlert();
        });
        let renameAction:UITableViewRowAction = UITableViewRowAction(style: .normal, title: "重命名", handler: { (rowAction, indexPath) in
            self.editingTag = self.tagsController.object(at: indexPath) as Tag;
            self.tagNewView.showWithMask(self.editingTag);
        });
        return [deleteAction,renameAction];
    }();
    
    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        return self.cellEditActions;
    }
    
    func showDeleteConfirmAlert() -> Void {
        UIAlertController.standardAlert("确定", message: "是否删除\"\(String(describing: self.editingTag!.name))\"", okAction: {
            self.editingTag?.deleteFromContext();
            self.editingTag = nil;
            HStoreManager.defaultManger().saveContext();
        }) {
            if (self.actionFinishHandler != nil){
                self.actionFinishHandler!(true);
            }
            self.editingTag = nil;
            }.show();
    }
    
    var actionFinishHandler:((Bool) -> ())?;
    @available(iOS 11.0, *)
    lazy var trailingConfiguration:UISwipeActionsConfiguration = {
        let deleteAction:UIContextualAction = UIContextualAction(style: UIContextualAction.Style.destructive, title: "删除", handler: { (action, view, closure) in
            self.actionFinishHandler = closure;
            self.showDeleteConfirmAlert();
        });
        var configruation:UISwipeActionsConfiguration = UISwipeActionsConfiguration(actions:[deleteAction]);
        return configruation;
    }();
    @available(iOS 11.0, *)
    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        self.editingTag = self.tagsController.object(at: indexPath) as Tag;
        return self.trailingConfiguration;
    }
    
    @available(iOS 11.0, *)
    lazy var leadingConfiguration:UISwipeActionsConfiguration = {
        let renameAction:UIContextualAction = UIContextualAction(style: UIContextualAction.Style.normal, title: "重命名", handler: { (action, view, closure) in
            self.tagNewView.showWithMask(self.editingTag);
            self.actionFinishHandler = closure;
        });
        var configruation:UISwipeActionsConfiguration = UISwipeActionsConfiguration(actions:[renameAction]);
        return configruation;
    }();
    @available(iOS 11.0, *)
    override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        self.editingTag = self.tagsController.object(at: indexPath) as Tag;
        return self.leadingConfiguration;
    }

}
